package zouran.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;
import zouran.entity.EarthquakeInfo;
import zouran.entity.IntensityLine;
import zouran.service.EarthquakeInfoService;

import java.io.IOException;
import java.net.URISyntaxException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * Author：zouran
 * Date：2023/3/10  16:30
 * Description:get data of earthquake util
 */
//@SpringBootTest
@Slf4j
@Component
public class EarthquakeDataUtil {
    //网站每页数据为15条，若要爬取全部数据则修改值为  Max_page=总数据/15，此处默认为1,检索最近15条地震(约一个月)是否在数据库
    public static int Max_page = 1;
    private final EarthquakeInfoService earthquakeInfoService;

    public EarthquakeDataUtil(EarthquakeInfoService earthquakeInfoService) {
        this.earthquakeInfoService = earthquakeInfoService;
    }

    //    @Test
    public void get_data() throws URISyntaxException, IOException {
        for (int page = 1; page <= Max_page; page++) {
            CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
            URIBuilder uriBuilder = new URIBuilder("https://www.cea.gov.cn/eportal/ui");
            uriBuilder.addParameter("pageId", "366506")
                    .addParameter("startDate", "2000-01-01 00:00:00")
                    .addParameter("endDate", DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00").format(LocalDateTime.now()))
                    .addParameter("startMagnitude", "0")
                    .addParameter("endMagnitude", "10")
                    .addParameter("areaname", "中国")
                    .addParameter("isshow", "yes")
                    .addParameter("currentPage", String.valueOf(page));
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36");
            CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpGet);
            String html = EntityUtils.toString(closeableHttpResponse.getEntity());
            Document document = Jsoup.parse(html);
            Elements table = document.getElementsByTag("table");
            Elements trList = table.get(0).getElementsByTag("tr");
            if (trList.size() == 1) break;
//            System.out.println(trList.size());
            for (int i = 1; i < trList.size(); i++) {
                Elements element = trList.get(i).getElementsByTag("td");
                String earthquakeName = element.get(6).text();
                Double magnitude = Double.valueOf(element.get(1).text());
                Double longitude = Double.valueOf(element.get(4).text());
                Double latitude = Double.valueOf(element.get(3).text());
                Double depth = null;
                if (!element.get(5).text().equals(""))
                    depth = Double.valueOf(element.get(5).text());
                LocalDateTime earthquakeTime;
                try {
                    earthquakeTime = LocalDateTime.parse((element.get(2).text()), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                } catch (DateTimeParseException ignored) {
                    try {
                        earthquakeTime = LocalDateTime.parse((element.get(2).text().split("\\.")[0]), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    } catch (DateTimeParseException e) {
                        try {
                            earthquakeTime = LocalDateTime.parse((element.get(2).text().split(":")[0] + ":" + element.get(2).text().split(":")[1] + ":59"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                        } catch (Exception exception) {
                            earthquakeTime = LocalDateTime.parse("2004-12-28 23:20:16", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                            exception.printStackTrace();
                        }
                    }
                }
                List<IntensityLine> list = new ArrayList<>();
                EarthquakeInfo earthquakeInfo = new EarthquakeInfo(null, earthquakeName, magnitude, null, longitude, latitude, depth, earthquakeTime, list);
                Double dividingLine = 105.0;
                log.info("data");
                System.out.println(earthquakeInfo);
                if (earthquakeInfo.getLongitude() < dividingLine) {
                    /*西部地区*/
                    earthquakeInfo.getIntensity(5.253, 1.398, 4.164, 26, 0, 2.019, 1.398, 2.943, 8, 0);
                } else {
                    /*东部地区*/
                    earthquakeInfo.getIntensity(5.019, 1.446, 4.136, 24, 0, 2.240, 1.446, 3.070, 9, 0);
                }
                try {
                    if (earthquakeInfoService.judgeEarthquakeInfoExist(earthquakeName, earthquakeTime)) {
                        log.info("当前数据已存在");
                    }
                    earthquakeInfoService.insertEarthquakeInfo(earthquakeInfo);
                } catch (Exception e) {
                    log.info("捕获插入异常");
//                    System.out.println(Arrays.toString(e.getStackTrace()).split(":")[0]);
//                    e.printStackTrace();
                }
                System.out.println(earthquakeInfo);
                log.info("success");
            }
            closeableHttpClient.close();
            closeableHttpResponse.close();
        }
    }

}
